package com.seari.gena.ciosClient;

import java.nio.charset.Charset;
import java.util.Properties;

import com.seari.gena.ciosClient.handler.CIOSNotifyServerHandler;
import com.seari.utils.PropertiesUtil;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;

public class CIOSNotifyServer {
	private final int port;

	public CIOSNotifyServer(int port) {
		this.port = port;
	}

	public void start() throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();

		EventLoopGroup group = new NioEventLoopGroup();
		try {
			ServerBootstrap sb = new ServerBootstrap();
			sb.option(ChannelOption.SO_BACKLOG, 1024);
			sb.group(group, bossGroup) // 绑定线程池
					.channel(NioServerSocketChannel.class) // 指定使用的channel
					.childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作

						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							System.out.println("客户端请求" + "IP:" + ch.localAddress().getHostName() + "Port:"
									+ ch.localAddress().getPort());
							ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
							ch.pipeline().addLast(new CIOSNotifyServerHandler()); //
							ch.pipeline().addLast(new ByteArrayEncoder());
						}
					});
			ChannelFuture cf = sb.bind(port).sync(); // 服务器异步创建绑定
			if (cf.isDone()) {
				System.out.println(CIOSNotifyServer.class + " 启动正在监听： " + cf.channel().localAddress());
			}
			cf.channel().closeFuture().sync(); // 关闭服务器通道
		} finally {
			group.shutdownGracefully().sync(); // 释放线程池资源
			bossGroup.shutdownGracefully().sync();
		}
	}

	public static void main(String[] args) throws Exception {
		Properties prop = PropertiesUtil.loadConfig("gena.properties");
		new Thread(new Runnable() {
			public void run() {
				try {
					new CIOSNotifyServer(Integer.parseInt(prop.getProperty("CIOSClientPort"))).start();// 启动监听
				} catch (Exception e) {
					e.printStackTrace();
				} 
			}
		}).start();
		new CIOSSubscribeClient(prop.getProperty("ATSServerIp1"), Integer.parseInt(prop.getProperty("ATSServerPort"))).setup();
	}
}
